/**
 Copyright (c) 2023, LXMS (lxinet.cn).

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */
import axios from "axios";
import {stringify} from 'qs';
import {localStorage, sessionStorage} from '@/utils/storage'
import {message, Modal} from 'ant-design-vue';

const errorTip = msg => {
  message.error(msg);
}

const service = axios.create({
  baseURL: "http://127.0.0.1:8200",
  timeout: 10000
})

let showLoginTimeOut = false;

//请求拦截
service.interceptors.request.use(
  config => {    //获取到缓存..中的token添加到请求头
    config.headers.Authorization = "Bearer " + localStorage.get("token")
    config.headers.curAgency = localStorage.get('orgInfo')?.orgCode || '';
    if (config.method.toLowerCase() === "get".toLowerCase()) {
      config.params = config.data || config.params;
    }
    return config
  },
  err => {
    errorTip(err)
    return Promise.reject(err)
  }
)
//响应拦截
service.interceptors.response.use(
  res => {  //代表网络请求成功了，stutas == 200
    //判断接口返回的数据， 这里我们后端也加了判断返回的 code 不等于 200 就没通过后端的校验
    console.log("response", res)
    if (res.data.code !== 0) {
      if (res.data.code === 10000007) {
        //登录超时
        if (!showLoginTimeOut) {
          showLoginTimeOut = true;
          Modal.error({
            title: '系统提示',
            content: res.data.msg,
            okText: "重新登录",
            onOk() {
              window.location.href = "/login";
            }
          });
        }
      } else {
        if (res.data.code === 10000008 && !localStorage.get("token")) {
          //无权限，且没有token，直接跳到登录页面
          window.location.href = "/login";
        } else {
          errorTip(res.data.msg)
        }
      }
      return Promise.reject(res.data)   //抛出异常
    } else {
      return Promise.resolve(res.data)
    }
  },
  error => {   //网络请求出错 判断状态码做出相应的操作
    let {response} = error
    switch (response.data.status) {  //可以单独封装出去
      case 404:
        errorTip(`${response.data.status}-->${response.data.message}`)
        break;
      case 403:
        errorTip(`${response.data.status}-->${response.data.message}`)
        break;
      default:
        errorTip(`${response.data.status}-->${response.data.message}`)
    }
    return Promise.reject(error)
  }
)

const installer = {
  vm: {},
  install(Vue, router = {}) {
    Vue.prototype.$request = service
  }
};

export {
  installer as VueAxios,
  service as request
}